package com.heima.leetcode.practice;

/**
 * @author 勾新杰
 * @version 1.0
 * @description: leetcode 117. 填充每个节点的下一个右侧节点指针 II
 * @date 2025/5/23 10:20
 */
public class E117 {

    public static class Node {
        public int val;
        public Node left;
        public Node right;
        public Node next;

        public Node() {
        }

        public Node(int _val) {
            val = _val;
        }

        public Node(int _val, Node _left, Node _right, Node _next) {
            val = _val;
            left = _left;
            right = _right;
            next = _next;
        }
    }

    /**
     * 依旧是层序遍历的思路
     * @param root 根节点
     * @return 填充节点的next指针后的根节点
     */
    public Node connect(Node root) {
        Node currLevel = root;
        while (currLevel != null) {
            Node sentinel = new Node(), curr = sentinel;
            while (currLevel != null) {
                if (currLevel.left != null) {
                    curr.next = currLevel.left;
                    curr = curr.next;
                }
                if (currLevel.right != null) {
                    curr.next = currLevel.right;
                    curr = curr.next;
                }
                currLevel = currLevel.next;
            }
            currLevel = sentinel.next;
        }
        return root;
    }
}
